package com.cloudbroker.bcs.platform.dav.middle.task;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.cloudbroker.bcs.platform.dav.common.util.SessionHelper;
import com.cloudbroker.bcs.platform.dav.middle.entity.Broker;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerService;
import com.cloudbroker.bcs.platform.dav.middle.service.CustomerBrokerRelService;
import com.cloudbroker.bcs.platform.dav.middle.service.CustomerService;
import com.cloudbroker.bcs.platform.dav.middle.task.base.SimpleLeaderTakeTask;

@Component
public class OnlineUpdateTask extends SimpleLeaderTakeTask {
    
    private static final Logger logger = LoggerFactory.getLogger(OnlineUpdateTask.class);
    
    @Resource
    private CustomerService customerService;
    
    @Resource
    private BrokerService brokerService;
    
    @Resource
    private CustomerBrokerRelService customerBrokerRelService;

    @Scheduled(cron="${task.onlineUpdateTask.execute.cron}")
    @Override
    public void doTask() {
        try {
            
            logger.info("***********************在线用户更新开始**************************");
            List<Broker> brokerList = brokerService.queryAll();
            for (Broker broker : brokerList) {
                String brokerId = String.valueOf(broker.getBroker_id());
                Set<String> newFansList = SessionHelper.getInstance().getNewOnlineList(brokerId);
                //把旧的缓存删除，把新的放到旧的里面
                SessionHelper.getInstance().destroyOldOnlineList(brokerId);
                if (newFansList != null && !newFansList.isEmpty()) {
                    String[] s = new String[newFansList.size()];
                    SessionHelper.getInstance().addListToBrokeyOnline(false, brokerId, newFansList.toArray(s));
                    customerBrokerRelService.updateDownlineStatusByBroker(brokerId, newFansList);
                }
                SessionHelper.getInstance().destroyNewOnlineList(brokerId);
            }
            logger.info("***********************在线用户更新结束**************************");
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
    }
    
}
